package com.spider.base;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import org.apache.commons.lang3.StringUtils;

import com.spider.util.SpiderCondition;
import com.spider.util.SpiderProperties;

public class GetExecute {
	
	
	/***线程池中，创建的最大的线程数*/
	private static int MAX_THREAD_NUM;
	private static ExecutorService fixedThreadPool = null; //获得固定数目的线程 在执行过程中不再 自动添加
	private static ExecutorService cachedThreadPool = null; // 根据执行的任务动态的 决定线程池的大小 
	private static ExecutorService singleThreadPool = null; //线程池大小为1， 单线程执行
	private static ScheduledExecutorService scheduleThreadpool = null; //创建 定时、周期执行的线程池
	
	private GetExecute(){}
	
	static{
		String max_num = SpiderProperties.getString(SpiderCondition.MAX_THREAD_NUM);
		if(StringUtils.isNotBlank(max_num)){
			MAX_THREAD_NUM = Integer.parseInt(max_num);
		}else{ //设置 线程数 为系统cpu 数+1
			MAX_THREAD_NUM = Runtime.getRuntime().availableProcessors()+1;
		}
	}
	
	/** 创建一个getFixedThreadPool ExecuteService
	 * @return
	 */
	public static ExecutorService getFixedThreadPool(){
		synchronized (GetExecute.class) {
			if(fixedThreadPool==null){
				fixedThreadPool = Executors.newFixedThreadPool(MAX_THREAD_NUM);
			}
		}
		return fixedThreadPool;
	}
	/** 创建一个getCachedThreadPool ExecuteService
	 * @return
	 */
	public static ExecutorService getCachedThreadPool(){
		synchronized (GetExecute.class) {
			if(cachedThreadPool==null){
				cachedThreadPool = Executors.newCachedThreadPool();
			}
		}
		return cachedThreadPool;
	}
	
	/** 创建一个getSingleThreadPool ExecuteService
	 * @return
	 */
	public static ExecutorService getSingleThreadPool(){
		synchronized (GetExecute.class) {
			if(singleThreadPool==null){
				singleThreadPool = Executors.newSingleThreadExecutor();
			}
		}
		return singleThreadPool;
	}
	
	/** 创建一个getScheduleThreadpool ExecuteService
	 * @return
	 */
	public static ScheduledExecutorService getScheduleThreadpool(){
		synchronized (GetExecute.class) {
			if(scheduleThreadpool==null){
				scheduleThreadpool = Executors.newScheduledThreadPool(MAX_THREAD_NUM);
			}
		}
		return scheduleThreadpool;
	}
	
}
